/*
 * @lc app=leetcode.cn id=1030 lang=javascript
 *
 * [1030] 距离顺序排列矩阵单元格
 */

// @lc code=start
/**
 * @param {number} R
 * @param {number} C
 * @param {number} r0
 * @param {number} c0
 * @return {number[][]}
 */
var allCellsDistOrder = function (R, C, r0, c0) {
  /**
   * @type {number[][]}
   */
  const bucket = [];
  for (let i = 0; i < R; i++) {
    for (let j = 0; j < C; j++) {
      let index = getDist(i, j, r0, c0);
      if (!bucket[index]) {
        bucket[index] = [];
      }
      bucket[index].push([i, j]);
    }
  }
  const maxDist = Math.max(r0, R - 1 - r0) + Math.max(c0, C - 1 - c0);
  const result = [];

  for (let i = 0; i <= maxDist; i++) {
    result.push(...bucket[i]);
  }

  return result;

  /**
   * @description: 获取2点之间的曼哈顿距离
   * @param {number} r1
   * @param {number} c1
   * @param {number} r0
   * @param {number} c0
   * @return {number}
   */
  function getDist(r1, c1, r0, c0) {
    return Math.abs(r1 - r0) + Math.abs(c1 - c0);
  }
};
// @lc code=end
